package ds.adt;

import java.util.Iterator;

/**
 * Implements Queue data structure.
 *
 * @author shankar
 *
 * @param <Item>
 */
public class Queue<Item> implements Iterable<Item> {

	private Node first;
	private Node last;
	private int N;

	public Queue() {
	}

	public boolean isEmpty() {
		return (first == null);
	}

	public int size() {
		return N;
	}

	public void enqueue(Item item) {
		Node oldLast = last;
		last = new Node();
		last.data = item;
		last.next = null;
		if (isEmpty()) {
			first = last;
		} else {
			oldLast.next = last;
		}
		N++;
	}

	public Item dequeue() {
		Item item = first.data;
		first = first.next;
		if (isEmpty()) {
			last = null;
		}
		N--;
		return item;
	}

	private class Node {
		private Item data;
		private Node next;
	}

	@Override
	public Iterator<Item> iterator() {
		return new ListIterator();
	}

	private class ListIterator implements Iterator<Item> {

		private Node current = first;

		@Override
		public boolean hasNext() {
			return (current != null);
		}

		@Override
		public Item next() {
			Item item = current.data;
			current = current.next;
			return item;
		}

		@Override
		public void remove() {
		}
	}

}
